package cn.tedu.order.service.impl;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.Set;

@Component
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private StorageClient storageClient;
    /*使用seata全局事务时，需要开启全局事务
    * 使用@GlobalTransactional  注解开启全局事务
    * 只需要在第一个模块上添加就可以*/
    @GlobalTransactional
    @Transactional  //同时也要添加注解控制本地事务
    @Override
    public void create(Order order) {
        //从全局唯一id发号器获得id
        String id = easyIdClient.getNextId("order_business");
        Long orderId = Long.valueOf(id);
        //Long orderId = Math.abs(new Random().nextLong());
        order.setId(orderId);
        orderMapper.create(order);

        //远程调用storage，减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用account，扣减账户
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
